package models;

import controllers.GameController;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.node.ObjectNode;
import play.libs.F;
import play.mvc.WebSocket;

/**
 * Created with IntelliJ IDEA.
 * User: chlemke
 * Date: 27.12.13
 * Time: 18:14

 */
public class GameConnection {

    private GameWebSocket gameWebSocket;
    private GameController gameController;
    private String mapSize;

    public GameConnection(GameController gameController, String mapSize) throws Exception{
        this.gameController = gameController;
        this.mapSize = mapSize;
        this.gameWebSocket = new GameWebSocket(this, gameController);
    }

    public GameWebSocket getWebSocket(){
        return gameWebSocket;
    }

    public void gameConnectionReady(){
        gameController.initGame(mapSize);
    }

    public void onReceive(JsonNode node) {
        System.out.println(node);
        String kind = node.get("kind").asText();

        if(kind.equals("Command")){
            String command = node.get("command").asText();

            switch (command){
                case "NextWave":
                    gameController.nextWave();
                    break;
                case "UpdateTower":
                    gameController.updateTower(node.get("posx").asInt(), node.get("posy").asInt());
                    break;
                case "BuildTower":
                    gameController.buildTower(node.get("posx").asInt(), node.get("posy").asInt(), node.get("towersize").asInt());
                    break;
            }
        }
    }

    public void send(ObjectNode json) {
        gameWebSocket.send(json);
    }


}
